package org.flower.web.servlet;

import com.alibaba.fastjson.JSON;
import org.flower.dao.CommodityDetailsDao;
import org.flower.dao.impl.CommodityDetailsDaoImpl;
import org.flower.entity.CommodityDetails;
import org.flower.utils.RandomCommoditys;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 *  随机展示商品的servelt
 */
@WebServlet(urlPatterns="/randomCommoditys.shtml")
public class RandomCommoditysServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理字符编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取输出对象
        PrintWriter out = response.getWriter();
        CommodityDetailsDao cdao = new CommodityDetailsDaoImpl();
        //要返回的商品集合
        List<CommodityDetails> commList = new ArrayList<CommodityDetails>();
        //获取参数 要查询的商品数量
        String comNum = request.getParameter("number");
        List<Integer> ids = RandomCommoditys.getCommodityIds(42, Integer.parseInt(comNum));
        for(int i : ids){
            //循环获取商品信息
            CommodityDetails com = cdao.getComdetailsById(i);
            //处理商品图片
            String img = com.getComImage().split(",")[0];
            //将处理好的商品图片 重新赋值（还给它）
            com.setComImage(img);
            commList.add(com);
        }
        //将集合对象输出
        out.print(JSON.toJSONString(commList));
    }
}
